<template>
  <div v-loading="uploading" style="width: 100%">
    <div class="flex align-end" style="width: 100%">
      <el-upload
        drag
        :action="uploadUrl"
        accept="image/*,.mp3,.m4a,video/*"
        multiple
        :before-upload="beforeUpload"
        :on-success="(response, file, fileList) => { return uploadVideoSuccess(response, file, fileList, 'time') }"
        :limit="99"
        :on-error="handleUploadError"
        :show-file-list="false"
        v-if="!readonly"
        style="width: 100%"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          拖拽图片、录音、视频或者<em>点击或者拖拽上传</em>
        </div>
      </el-upload>
      <el-button
        type="primary"
        plain
        icon="View"
        v-if="fileUrl || readonly"
        @click="preview"
        class="no-shrink"
      >查看凭证</el-button>
    </div>
    <div @paste="handlePaste"
         style="width: 100%;height: 40px"
         class="flex align-center justify-center cursor-pointer text-blue"
         v-if="!readonly"
    >
      点击此处后,Ctrl+V上传
    </div>
  </div>

  <el-dialog
    width="600px"
    :title="`查看${fileType}`"
    v-model="dialogVisible"
  >
    <div class="flex align-center justify-center">
      <video
        controls
        height="330"
        width="500"
        v-if="fileType === '视频'"
      >
        <source :src="fileUrl">
        <embed
          height="50"
          width="300"
          :src="fileUrl"
        >
      </video >
      <audio
        controls
        height="100"
        width="300"
        v-if="fileType === '音频'"
      >
        <source :src="fileUrl">
        <embed
          height="50"
          width="300"
          :src="fileUrl"
        >
      </audio>
      <el-image v-if="fileType === '图片'" style="width: 90%; margin-left: 5%" :src="fileUrl" fit="fill" />
    </div>
  </el-dialog>
</template>

<script setup>
import request from '@/util/request.ts';
import {getCurrentInstance, ref, watch} from 'vue';
import {ElMessage} from 'element-plus';

const { proxy } = getCurrentInstance()

const uploadUrl = '/production/files/upload';
const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false
  }
})
const fileType = ref('')
const dialogVisible = ref(false);
const preview = () => {
  if (!fileUrl.value) {
    return ElMessage.warning('未上传处理凭证')
  }
  dialogVisible.value = true;
}
const fileUrl = ref('')

watch(() => props.url, (newVal, oldVal) => {
  if (!newVal) return
  fileType.value = getFileTypeFromURL(newVal);
  if (fileType.value === '未知类型') {
    ElMessage.warning('上传的文件类型不支持查阅')
    fileUrl.value = '';
  }
  fileUrl.value = newVal;
}, {
  immediate: true
})
const beforeUpload = (file) => {
  let fileType = file.name.split('.').pop();
  proxy.$message.success(`识别当前文件类型为${getFileCategory(fileType)}`)
  const isLt2M = file.size / 1024 / 1024 < 20;
  if (!isLt2M) {
    ElMessage.warning("上传文件大小不能超过 20MB!");
    return false;
  }
  uploading.value = true
  return true;
};
const emit = defineEmits(['update:fileUrl']);
const uploadVideoSuccess = (res, file, fileList, type) => {
  if (res.success) {
    ElMessage.success('上传成功');
    fileUrl.value = res.data;
    fileType.value = getFileTypeFromURL(res.data);
    emit('update:fileUrl', res.data)
  } else {
    ElMessage.warning('上传失败');
  }
  uploading.value = false;
};
const handleUploadError = (error, uploadFile, uploadFiles) => {
  uploading.value = false;
  proxy.$message.error(error.toString());
}
function getFileTypeFromURL(url) {
  const urlObj = new URL(url);
  const path = urlObj.pathname;

  const fileName = path.split('/').pop(); // 获取最后一个斜杠后面的字符串
  const fileExtension = fileName.split('.').pop().toLowerCase();

  return getFileCategory(fileExtension);
}
function getFileCategory(extension) {
  // 文件类型映射表
  const fileTypeMap = {
    // 图片文件扩展名
    jpg: '图片',
    jpeg: '图片',
    png: '图片',
    gif: '图片',
    bmp: '图片',
    svg: '图片',
    tiff: '图片',
    webp: '图片',

    // 视频文件扩展名
    mp4: '视频',
    avi: '视频',
    mov: '视频',
    mpeg: '视频',
    mkv: '视频',
    flv: '视频',
    webm: '视频',

    // 音频文件扩展名
    mp3: '音频',
    wav: '音频',
    aac: '音频',
    flac: '音频',
    ogg: '音频',
    m4a: '音频',
  };

  return fileTypeMap[extension.toLowerCase()] || '未知类型';
}

const uploading = ref(false)
const handlePaste = (e) => {
  uploading.value = true;
  const items = e.clipboardData?.items;
  if (!items) return;

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const type = item.type.split('/')[0];
    if (item.kind === 'file' && ['audio', 'video', 'image'].includes(type)) {
      const file = item.getAsFile();
      if (file) {
        const form = new FormData();
        form.append('file', file);
        request.post('/production/files/upload', form).then(res => {
          uploading.value = false;
          let { data, success } = res;
          if (success) {
            ElMessage.success('上传成功');
            fileUrl.value = res.data;
            fileType.value = type === 'image' ? '图片' : type === 'audio' ? '音频' : '视频';
            emit('update:fileUrl', res.data)
          }
        }).then(() => {
          uploading.value = false;
        });
      } else {
        uploading.value = false;
        ElMessage.warning('无效文件');
      }
    } else {
      uploading.value = false;
      ElMessage.warning('粘贴内容非图片,视频或音频');
    }
  }
  uploading.value = false;
}
</script>

<style scoped lang="scss">

</style>